using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Jaws.Core.Web.Entities;
using Jaws.Core.Web.Entities.Recipes;
using Jaws.Core.Web.Entities.Validation.Entities;

namespace Jaws.Web.Mvc.Controllers
{
    public class RecipesController : Controller
    {

        private Recipes recipes;

        public RecipesController()
        {
            recipes = XmlCollectionBase<Recipes, Recipe>.Load();
        }

        //
        // GET: /Default1/

        public ActionResult Index()
        {
            return View(recipes);
        }

        //
        // GET: /Default1/Details/5

        public ActionResult Details(Guid id)
        {
            return View(recipes[id]);
        }

        //
        // GET: /Default1/Create

        public ActionResult Create()
        {
            return View(new Recipe());
        }

        //
        // POST: /Default1/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                var recipe = new Recipe
                                  {
                                      Ingredients = Regex.Split(collection["Ingredients"], "\r\n").ToList(),
                                      Instructions = collection["Instructions"],
                                      Name = collection["Name"]
                                  };
                recipes.Add(recipe);
                recipes.Save();
                foreach (BrokenRule brokenRule in recipe.BrokenRules)
                {
                    ModelState.AddModelError(brokenRule.PropertyName, brokenRule.Message);
                }
                //if (!ModelState.IsValid)
                //    return View(recipe);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Default1/Edit/5

        public ActionResult Edit(Guid id)
        {
            return View(recipes[id]);
        }

        //
        // POST: /Default1/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
